﻿using System;
using System.Web.Mvc;
using CharacterModel;
using Framework.Model;
using System.Linq;
using Ninject;

namespace MvcApplication1.Controllers
{
    public class MarkersController : Controller
    {
        [Inject]
        public Repository Repository { get; set; }

        public ActionResult Set()
        {
            return View();
        }

        public ActionResult Save(FeatureMarkers featureMarkers)
        {
            var feature = Repository.Get<Feature>(featureMarkers.FeatureId);
            feature.MarkerPoints = featureMarkers
                .Markers
                .Select(marker => new MarkerPoint
                                      {
                                          PointX = marker.X,
                                          PointY = marker.Y,
                                          MarkerPointType =
                                              new MarkerPointType
                                                  {
                                                      MarkerPointTypeEnum =
                                                          (MarkerPointTypeEnum)
                                                          Enum.Parse(typeof (MarkerPointTypeEnum), marker.MarkerName)
                                                  }
                                      })
                .ToList();

            feature.MarkerPoints = feature
                .MarkerPoints
                .GroupBy(m => m.MarkerPointType.Id)
                .Select(g => g.First())
                .ToList();

            Repository.Save(feature);

            return Json(new {Result = "success"});
        }

        public class FeatureMarkers
        {
            public int FeatureId { get; set; }
            public MarkerData[] Markers { get; set; }
        }

        public class MarkerData
        {
            public double X { get; set; }
            public double Y { get; set; }
            public string MarkerName { get; set; }
        }
    }
}